package com.chunayev.numerology.gui.table;

import java.awt.Dimension;

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;

import com.chunayev.numerology.domain.PositionSummary;
import com.chunayev.numerology.gui.action.SummaryTokenChangeNotifier;
import com.chunayev.numerology.util.db.DBInitializer;
import com.sleepycat.je.DatabaseException;

/**
 * @author Sergey Chunayev
 */
@SuppressWarnings("serial")
public class NameCalculationsTable extends JTable implements
        SummaryTokenChangeNotifier {
    
    private String token;
    private int position;
    
    /**
     * 
     */
    public NameCalculationsTable() {
        super(new NameCalculationsTableModel());
        getTableHeader().setReorderingAllowed(false);
        final Dimension d = getPreferredScrollableViewportSize();
        d.height = 120;
        setPreferredScrollableViewportSize(d);
    }
    
    @SuppressWarnings("unchecked")
    public <T> T getGenericValueAt(final int row, final int column) {
        return (T) super.getValueAt(row, column);
    }
    
    /*
     * (non-Javadoc)
     * @see javax.swing.JTable#getModel()
     */
    @Override
    public NameCalculationsTableModel getModel() {
        return (NameCalculationsTableModel) super.getModel();
    }
    
    /*
     * (non-Javadoc)
     * @see
     * com.chunayev.numerology.gui.action.SummaryTokenChangeNotifier#getSummary
     * ()
     */
    @Override
    public PositionSummary getSummary() throws DatabaseException {
        return DBInitializer.SUMMARY_PRIMARY_INDEX.get((long) this.position);
    }
    
    /*
     * (non-Javadoc)
     * @see
     * com.chunayev.numerology.gui.action.SummaryTokenChangeNotifier#getToken()
     */
    @Override
    public String getToken() {
        return this.token;
    }
    
    /*
     * (non-Javadoc)
     * @see
     * com.chunayev.numerology.gui.action.SummaryTokenChangeNotifier#update()
     */
    @Override
    public void update() {
        
    }
    
    /*
     * (non-Javadoc)
     * @see
     * javax.swing.JTable#valueChanged(javax.swing.event.ListSelectionEvent)
     */
    @Override
    public void valueChanged(final ListSelectionEvent e) {
        super.valueChanged(e);
        if (!e.getValueIsAdjusting()) {
            ListSelectionModel model = (ListSelectionModel) e.getSource();
            int index = model.getAnchorSelectionIndex();
            if (index != -1) {
                this.token = this.<String> getGenericValueAt(index, 0);
                this.position = this.<Integer> getGenericValueAt(index, 2);
            }
        }
    }
}
